package com.polaris.live.adapter

import android.animation.Animator
import android.animation.ValueAnimator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import com.bumptech.glide.Glide
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.polaris.live.R
import com.polaris.live.common.constant.AppConst
import com.polaris.live.databinding.AdapterLiveBroadBinding
import com.polaris.live.utils.image.loadImage
import com.polaris.live.utils.livehelper.LiveStateBean
import com.polaris.live.utils.zego.LiveActivityIdentifier
import com.polaris.live.utils.zego.LiveEngineManage
import com.polaris.live.utils.zego.LivePlayer
import com.polaris.live.utils.zego.listener.OnLivePlayListenerImpl
import im.zego.zegoexpress.constants.ZegoPlayerState
import im.zego.zegoexpress.constants.ZegoRemoteDeviceState
import im.zego.zegoexpress.constants.ZegoStreamQualityLevel
import im.zego.zegoexpress.entity.ZegoPlayStreamQuality
import jp.wasabeef.glide.transformations.BlurTransformation
import org.json.JSONObject

/**
 * LiveBroadAdapter
 *
 * @author Created by 天晴 on 2023/10/13/013 17:21
 */
class LiveBroadAdapter(val owner: LifecycleOwner) :
    BaseQuickAdapter<LiveStateBean, LiveBroadAdapter.PlayViewHolder>(R.layout.adapter_live_broad) {

    override fun onCreateDefViewHolder(parent: ViewGroup, viewType: Int): PlayViewHolder {
        return PlayViewHolder(
            AdapterLiveBroadBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        )
    }

    override fun convert(holder: PlayViewHolder, item: LiveStateBean) {
        holder.binding.apply {
            holder.isRecycle = false
            val data = item.displayUserBean
            if (data != null) {
                if (item.playNow && data.base.living == AppConst.YES) {
                    start(holder, item)
                }
                if (data.base.calling == AppConst.YES) {
                    Glide.with(cover.context)
                        .loadImage(data.cover)
                        .into(cover)
                } else {
                    Glide.with(cover.context)
                        .loadImage(data.cover)
                        .transform(BlurTransformation(15, 15))
                        .into(cover)
                }
            } else {
                cover.setImageResource(0)
            }
        }
    }

    override fun convert(holder: PlayViewHolder, item: LiveStateBean, data: List<Any>) {
        if (data.isNotEmpty()) {
            if (data[0] == "notify") {
                item.displayUserBean?.let {
                    if (it.base.living == AppConst.YES) {
                        it.playStreamId?.let { streamId ->
                            LiveEngineManage.getEngine()?.takePlayStreamSnapshot(
                                streamId
                            ) { code, image ->
                                if (code == 0) {
                                    if (!holder.isRecycle) {
                                        holder.binding.cover.setImageBitmap(image)
                                    }

                                }
                            }
                        }
                    }
                }
            } else if (data[0] == "start") {
                start(holder, item)
            }
        }

    }

    override fun onViewRecycled(holder: PlayViewHolder) {
        super.onViewRecycled(holder)
        holder.isRecycle = true
    }

    private fun start(holder: PlayViewHolder, item: LiveStateBean) {
        if (owner.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) {
            val streamId = item.displayUserBean?.playStreamId
            if (streamId != null) {
                LivePlayer.startLive(
                    streamId, holder.binding.remoteUserView,
                    LiveActivityIdentifier.LIVE_BROADCAST_FRAGMENT, false, holder.listener
                )
            }
        }
    }

    inner class PlayViewHolder(val binding: AdapterLiveBroadBinding) :
        BaseViewHolder(binding.root) {

        private var mValueAnimator: ValueAnimator? = null
        var isRecycle = false
        var onPlayerRenderVideoFirstFrame = false //第一帧是否渲染
        val listener = object : OnLivePlayListenerImpl() {
            override fun onPlayStart() {
            }

            override fun onPlayStop() {
                onPlayerRenderVideoFirstFrame = false
                binding.remoteUserView.visibility = View.GONE
            }

            override fun onPlayerRenderVideoFirstFrame() {
                onPlayerRenderVideoFirstFrame = true
                animShowLive()
            }

            override fun onPlayerQualityUpdate(quality: ZegoPlayStreamQuality) {
                when (quality.level) {//拉流质量的综合分数
                    ZegoStreamQualityLevel.EXCELLENT -> { //非常好

                    }

                    ZegoStreamQualityLevel.GOOD -> { //好

                    }

                    ZegoStreamQualityLevel.MEDIUM -> { //一般

                    }

                    ZegoStreamQualityLevel.BAD -> { //差

                    }

                    ZegoStreamQualityLevel.DIE -> { //失败

                    }

                    ZegoStreamQualityLevel.UNKNOWN -> { //未知

                    }
                }
            }

            override fun onPlayerStateUpdate(
                state: ZegoPlayerState?,
                errorCode: Int,
                extendedData: JSONObject?
            ) {
                if (state == ZegoPlayerState.NO_PLAY && errorCode != 0) { //拉流失败
                    animHideLive()
                } else if (state == ZegoPlayerState.PLAY_REQUESTING && errorCode == 0) { //重试拉流

                }
            }

            override fun onRemoteSpeakerStateUpdate(state: ZegoRemoteDeviceState) {
                if (state == ZegoRemoteDeviceState.OPEN) {
                    animShowLive()
                } else {
                    animHideLive()
                }

            }
        }

        private fun animShowLive() {  //动画开启直播界面
            mValueAnimator?.takeIf { it.isRunning }?.apply {
                cancel()
                mValueAnimator = null
            }
            binding.remoteUserView.visibility = View.VISIBLE
            mValueAnimator = ValueAnimator.ofFloat(0f, 1f).apply {
                interpolator = LinearInterpolator()
                duration = 300
                repeatCount = 0
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    binding.remoteUserView.alpha = value
                }
                start()
            }

        }

        private fun animHideLive() { //动画关闭直播界面
            mValueAnimator?.takeIf { it.isRunning }?.apply {
                cancel()
                mValueAnimator = null
            }
            mValueAnimator = ValueAnimator.ofFloat(1f, 0f).apply {
                interpolator = LinearInterpolator()
                duration = 300
                repeatCount = 0
                addUpdateListener { animation ->
                    val value = animation.animatedValue as Float
                    binding.remoteUserView.alpha = value
                }
                addListener(object : Animator.AnimatorListener {
                    override fun onAnimationStart(animation: Animator) {
                    }

                    override fun onAnimationEnd(animation: Animator) {
                        binding.remoteUserView.visibility = View.GONE
                    }

                    override fun onAnimationCancel(animation: Animator) {
                        binding.remoteUserView.visibility = View.GONE
                    }

                    override fun onAnimationRepeat(animation: Animator) {
                    }
                })
                start()
            }

        }
    }

}
